package com.orcsystem.product.app;

import com.orcsystem.common.utils.PageUtils;
import com.orcsystem.common.utils.R;
import com.orcsystem.common.valid.AddGroup;
import com.orcsystem.common.valid.UpdateStatusGroup;
import com.orcsystem.product.entity.BrandEntity;
import com.orcsystem.product.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;


/**
 * 品牌
 *
 * @author aihs
 * @email aihs_work@163.com
 * @date 2020-04-29 14:16:13
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = brandService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    public R info(@PathVariable("brandId") Long brandId) {
        BrandEntity brand = brandService.getById(brandId);
        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    // 添加组的校验方式
    public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand /** ,BindingResult
     result */) {
//        if (result.hasErrors()){
//            // 有错误
//            HashMap<Object, Object> map = new HashMap<>();
//            result.getFieldErrors().forEach(item ->{
//                // 错误提示信息
//                String message = item.getDefaultMessage();
//                String field = item.getField();
//                map.put(field,message);
//            });
//            return Res.error(400,"存在错误").put("data",map);
//        }else {
//            // 没错误
//            brandService.save(brand);
//        }
        brandService.save(brand);
        return R.ok();
    }

    /**
     * 批量修改
     */
    @RequestMapping("/updateList")
    public R update(@RequestBody BrandEntity[] brands) {
        brandService.updateBatchById(Arrays.asList(brands));
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@Validated @RequestBody BrandEntity brand) {
        brandService.updateDetail(brand);
        return R.ok();
    }

    /**
     * 修改状态
     */
    @RequestMapping("/update/status")
    public R updateStatus(@Validated(UpdateStatusGroup.class) @RequestBody BrandEntity brand) {
        brandService.updateById(brand);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] brandIds) {
        brandService.removeByIds(Arrays.asList(brandIds));
        return R.ok();
    }

}
